package demo;

import java.util.Arrays;
import java.util.Comparator;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2022-11-16
 * Time: 22:01
 */
//没有传比较器，可以自己设置默认的Comparable<T>，两者可同时存在
    //缺点是比较死板
//class Student implements Comparable<Student>{
//    public String name;
//    public int age;
//    public int score;
//
//    public Student(String name, int age, int score) {
//        this.name = name;
//        this.age = age;
//        this.score = score;
//    }
//
//    @Override
//    public String toString() {
//        return "Student{" +
//                "name='" + name + '\'' +
//                ", age=" + age +
//                ", score=" + score +
//                '}';
//    }
//
//    @Override
//    //缺点写死比较的方法
//    public int compareTo(Student o) {
//        //return this.age - o.age;
//        return o.age - this.age;
//    }
//}


class Student implements Comparable<Student>{
    public String name;
    public int age;
    public int score;

    public Student(String name, int age, int score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", score=" + score +
                '}';
    }

//默认的比较
    @Override
    public int compareTo(Student o) {
        return this.age - o.age;
    }
}
//灵活的比较器
//自己的排序方法
class AgeCompartor implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        //年龄比较大小
        return o2.age - o1.age;
//        //小大
//        return o1.age - o2.age;
    }
}

class NameCompartor implements Comparator<Student>{

    @Override
    public int compare(Student o1, Student o2) {
        //name是字符串类型，内置comparable接口，直接使用compareTo比较字符串
        return o1.name.compareTo(o2.name);
    }
}


public class Test {
    public static void main(String[] args) {
        Student[] student = new Student[3];
        student[2] = new Student("a张三", 10, 80);
        student[1] = new Student("b李二", 9, 70);
        student[0] = new Student("c王一", 8, 60);
        AgeCompartor ageCompartor = new AgeCompartor();
        NameCompartor nameCompartor = new NameCompartor();
        //默认比较方法
        System.out.println("默认" + Arrays.toString(student));
        //与C语言的qsort类似，自己写一个排序方法
        Arrays.sort(student, ageCompartor);
        System.out.println("age" + Arrays.toString(student));
        Arrays.sort(student, nameCompartor);
        System.out.println("name" + Arrays.toString(student));
    }
}
